import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import XLSX from "xlsx";
import { Row, Button, Skeleton, Table, message } from 'antd';
import { TOTAL } from '../enum';
import { TotalItem } from '../styled';

import { exportExcl } from '@/utils/xlsx';
import { isNumber } from '@/utils/util';

interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  loading?: boolean,
  buttons?: Array<any>,
  total?: object,
  statisticalIndex?: Array<any>,
}

@connect(({ analyse_device, loading }) => ({
  total: analyse_device.total || {},
  statisticalIndex: analyse_device.statisticalIndex || [],
  loading: loading.effects['analyse_device/queryInfo']
}))
class index extends Component<IProps> {
  componentDidMount = () => {
    message.loading('', 0.6);
    const { dispatch } = this.props;
    dispatch({ type: 'analyse_device/queryInfo' });
  };

  toPercentage(value = 0) {
    return `${isNumber(+value) ? (+value * 100).toFixed(2) : 0} %`;
  }

  handleExport = e => {
    const { statisticalIndex, total = {} } = this.props;

    statisticalIndex.push({
      kindName: '合计',
      ...total
    });

    const ans = statisticalIndex && Array.isArray(statisticalIndex) && statisticalIndex.map(item => {
      return {
        '类型': item.kindName,
        '总数': item.totalCount,
        '完好数': item.goodCount,
        '损坏数': item.badCount,
        '故障率': isNumber(+item.malfunctionRate) ? `${(+item.malfunctionRate * 100).toFixed(2)}%` : '0%',
      }
    });

    exportExcl({
      XLSX,
      data: ans,
      name: "设备统计",
      fileName: "设备统计"
    })
  };

  render() {

    const { loading, statisticalIndex = [], total = {} } = this.props;
    const columns = [
      { dataIndex: 'kindName', title: '类型' },
      { dataIndex: 'totalCount', title: '总数' },
      {
        dataIndex: 'goodCount',
        title: '完好数',
        render: (value, record) => (
          <Link
            to={`/data/analyse_device/deviceFireHost?status=1&type=${record.kind}`}
            onClick={() => {
              sessionStorage.setItem('deviceRecord', JSON.stringify(record));
            }}
          >{value}</Link>
        )
      },
      {
        dataIndex: 'badCount',
        title: '损坏数',
        render: (value, record) => (
          <Link
            to={`/data/analyse_device/deviceFireHost?status=2&type=${record.kind}`}
            onClick={() => {
              sessionStorage.setItem('deviceRecord', JSON.stringify(record));
            }}
          >{value}</Link>
        )
      },
      { dataIndex: 'malfunctionRate', title: '故障率' },
    ];

    const ans = statisticalIndex && Array.isArray(statisticalIndex) && statisticalIndex.map((it, index) => ({
      ...it,
      key: index,
      kind: it.kind,
      malfunctionRate: `${(+it.malfunctionRate * 100).toFixed(2)}%`,
    }));

    return (
      <>
        <Row style={{'margin': '15px 30px'}}>
          {
            Array.isArray(TOTAL) && TOTAL.map((it, index) => (
              <TotalItem span={3} key={index}>
                <img src={it.icon} alt="" style={{'marginRight': '10px'}}/>
                <span>{ it.name }: </span>
                <span>{ it.func ? this[it.func](total[it.key]) : total[it.key] }</span>
              </TotalItem>
            ))
          }
          <TotalItem span={10}></TotalItem>
          <TotalItem span={2}>
            <Button onClick={this.handleExport}>导出</Button>
          </TotalItem>
        </Row>
        <Row>
          <Skeleton loading={loading} active>
            <Table
              columns={columns}
              dataSource={ans}
              bordered
              loading={this.props.loading}
              pagination={false}
            />
          </Skeleton>
        </Row>
      </>
    )
  }
}

export default index;
